# --*-- conding:utf-8 --*--
# @Time : 2025/6/16 10:39
# @Author : Xu
# @Email : wsxzy98@outlook.com
# @File : stock_move_line.py
# @Software : VScode

from odoo import models, fields, api

class StockMoveLine(models.Model):
    _inherit = 'stock.move.line'

    # 新增自定义字段
    origin_name = fields.Char(string='原产地')
    customer_reference = fields.Char(string='客户参考号')
    x_last_scan_time = fields.Datetime(string='最近扫描时间', readonly=True, copy=False, index=True)

    @api.model
    def create(self, vals):
        # 自动带出产品主数据origin
        if not vals.get('origin_name') and vals.get('product_id'):
            prod = self.env['product.product'].browse(vals['product_id'])
            if prod and prod.product_tmpl_id.origin:
                vals['origin_name'] = prod.product_tmpl_id.origin

        # 自动带出拣货单的客户参考号
        if not vals.get('customer_reference') and vals.get('picking_id'):
            picking = self.env['stock.picking'].browse(vals['picking_id'])
            if picking and picking.customer_reference:
                vals['customer_reference'] = picking.customer_reference
        
        rec = super().create(vals)
        # 初始化最近扫描时间（仅当创建时已有 qty_done>0）
        try:
            if float(vals.get('qty_done') or 0) > 0:
                rec.with_context(skip_last_scan_time=True).write({
                    'x_last_scan_time': fields.Datetime.now(),
                })
        except Exception:
            pass
        return rec

    @api.onchange('product_id')
    def _onchange_product_id_origin_name(self):
        # 产品变化自动同步origin_name
        if self.product_id and not self.origin_name:
            self.origin_name = self.product_id.product_tmpl_id.origin
    
    @api.onchange('picking_id')
    def _onchange_picking_id_customer_reference(self):
        # picking变化自动带出客户参考号
        if self.picking_id and self.picking_id.customer_reference and not self.customer_reference:
            self.customer_reference = self.picking_id.customer_reference

    def write(self, vals):
        # 避免递归
        if self.env.context.get('skip_last_scan_time'):
            res = super().write(vals)
            if 'origin_name' in vals:
                for line in self:
                    if line.product_id:
                        line.product_id.product_tmpl_id.origin = vals['origin_name']
            return res

        # 记录 qty_done 真变更的行
        to_update = []
        if 'qty_done' in vals:
            for ml in self:
                try:
                    new_qty = float(vals.get('qty_done') or 0.0)
                    if float(ml.qty_done or 0.0) != new_qty:
                        to_update.append(ml.id)
                except Exception:
                    pass

        res = super().write(vals)

        # 同步到产品模版
        if 'origin_name' in vals:
            for line in self:
                if line.product_id:
                    line.product_id.product_tmpl_id.origin = vals['origin_name']

        # 更新最近扫描时间
        if to_update:
            self.browse(to_update).with_context(skip_last_scan_time=True).write({
                'x_last_scan_time': fields.Datetime.now(),
            })
        return res

